package cn.yzx.pethome.system.fastdfs.controller;

import cn.yzx.pethome.utils.AjaxResult;
import cn.yzx.pethome.utils.FastdfsUtil;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fast")
@Api(value = "文件上传API" , description = "文件上传下载的功能")
public class FastDFSController {
    //上传
    /*
    *@RequestPart 请求参数认证  required = true 意思是必传    value = "file" 前端请求的参数名叫file
    *
    *
    * */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file")MultipartFile file){
        try {
            byte[] bytes = file.getBytes();
            String filename = file.getOriginalFilename();//获取上传的文件的全名 包含了后缀名
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);//获取后缀名
            String uploadPath = FastdfsUtil.upload(bytes, suffix);//返回的就是上传文件的路径  包含了组的
            return AjaxResult.success().setData(uploadPath);//直接返回了组 让前端做分割  也可以在后端做分割再传给前端
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("服务器或资源存在异常，请联系网管");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常，请稍后再试");
        }
    }
    //删除
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "file") String path){
        try {
            //传进来的参数  /group1/M00/00/00/wKgZhVkMP4KAZEy-AAA-tCf93Fo973.jpg
            //处理为       group1/M00/00/00/wKgZhVkMP4KAZEy-AAA-tCf93Fo973.jpg
            //处理        group1
            //处理        /M00/00/00/wKgZhVkMP4KAZEy-AAA-tCf93Fo973.jpg
            String filePath = path.substring(1);
            String group = filePath.substring(0, filePath.indexOf("/"));
            String bodyPath = filePath.substring(filePath.indexOf("/") + 1);
            FastdfsUtil.delete(group,bodyPath);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("服务器或资源存在异常，请联系网管");
        }
    }
    //下载
}
